<?php
/**
*比赛配置的控制管理
*比赛属于赛事，作为赛事的下一层级
*一个比赛可包含多局比赛
*@author susy.liang<liangling@ilngyuan.com.cn>
*/
namespace Admin\Controller;

class RaceGroupController extends BaseManageController {

	/**
	*模型表对象名
	*@var string
	*@access protected
	*/
	protected $modelName = 'Common/RaceGroup';

	/**
	*删除类型
	*@var bool false|逻辑删除 true|物理删除
	*@access protected
	*/
	protected $is_del 	 = false;

	/**
	*跳转的Url
	*@var string
	*@access protected
	*/
	protected $jumpAct	= 'RaceGroup/index';

	/**
	*模型项的相应值的文本描述
	*@var array
	*@access protected
	*/
	protected $text_map = array(
		'status' => array( 0 => '禁用', 1 => '开启', -1 => '删除')
	);

	public function _before_index()
	{
		$title = I('title');
		if($title)
			$search['title'] = array('like', (string)$title);

		/*$this->game = $game = I('get.game', 0, 'intval');
        if($game){
        	$search['game_id'] = $game;
        }*/
        
        $this->type = $type = I('get.type');
        if($type){
        	$curDate = date('Y-m-d', time());
        	switch ($type) {
        		case 'forcast':
                    $search['race_date'] = array('gt', $curDate);
        			break;
        		case 'normal':
        			$search['race_date'] = array('elt', $curDate);
        			break;
        	}
        }

        $this->match = $match = I('get.match', 0, 'intval');
        if($match){
        	$search['match_id'] = $match;
        }
		$this->where = $search;
 		
		$this->setMatch(true);
		//$this->setGame(true);
	}

	/**
	*新增比赛
	*/
	public function add(){
		if(IS_POST){
			$data = I('');
			$this->joiner($data);

			$data = $this->model->create($data);
			if($data)
				unset($data['id']);

			if($data && $id = $this->model->add($data)){
				$data['competitor'] && $this->addJoiner($data);

				$data['id'] = $id;
				// 上报比赛
				event('ResourceGroup')->storeRace($data);
				$this->success('操作成功');
			}else{
				$this->error($this->model->getError());
			}

		}else{

			$this->setMatch();
			//$this->setGame();

			$this->display('form');
		}
	}

	/**
	*比赛的编辑
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function edit($id){
		$id = intval($id);
		if(IS_POST){
			$data = I('');
			$data['id'] = $id;
			$this->joiner($data);
			$data = $this->model->create($data);
			if($data && $this->model->save($data)){
				$data['competitor'] && $this->addJoiner($data);
				// 上报比赛状态
				event('ResourceGroup')->updateRace($id);
				$this->success('更新成功');
			}else{
				$this->error($this->model->getError());
			}

		}else{
			$data = A('Api/RaceGroup', 'Event')->info($id);
			empty($data) && $this->error('非法操作项');
			$this->assign($data);

			$this->setMatch();

			$this->display('form');
		}
	}

	/**
	*赛事信息
	*/
	protected function setMatch($format=false)
	{
		$mdlObj = D('Admin/Match', 'Service');
		$matches = $mdlObj->where(array('status'=>$mdlObj::STATUS_PASS))
					->field('id,title')->select();
		if($format === false){
			$this->matches = $matches;
		}else{
			$temp = array();
			foreach ($matches as $key => $value) {
				$temp[$value['id']] = $value['title'];
			}

			$this->matches = $temp;
		}
		
	}

	/**
	*游戏信息获取
	*/
	private function setGame($format=false){

		$games = A('Api/Game', 'Event')->lists(array(), 'id,name');

		if($format===false){

			$this->games = $games;

		}else{

			$temp = array();
			foreach ($games as $key => $value) {
				$temp[$value['id']] = $value['name'];
			}

			$this->games = $temp;
		}
	}

	/**
	*参赛选手的处理
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	private function joiner(&$data){

		$competitor = array();

		if($data['fJoiner'] && $data['sJoiner']){
			array_push($competitor, htmlspecialchars($data['fJoiner']) );
			array_push($competitor, htmlspecialchars($data['sJoiner']) );

			$data['competitor'] = $competitor;
		}
		
		unset($data['fJoiner']);
		unset($data['sJoiner']);

		return true;
	}

	

	// 检查并添加队伍信息
	public function addJoiner($data)
	{
		$competitor = $data['competitor'];
		$model = D('Common/Team', 'Service');
		foreach ($competitor as $name) {
			$save['name'] 	     = $name;
			$save['full_name'] 	 = $name;
			$save['game_id'] = $data['game_id'];
			$save['status']  = $model::STATUS_PASS;
			$save = $model->create($save);
			$save && $model->add($save);
		}

		return true;
	}

	/** 
	 * 修改比赛的发布
	 * @author susy.liang<liangling@ilongyuan.com.cn>
	 * @param $id int 比赛组标识
	 *@param  $state int 发布状态 0|否 1|是
	 * @return 
	 */	
	public function changeState($id, $state = 0)
	{
		$id = intval($id);

		$servObj = D('Admin/Video', 'Service');
		$map = array(
				'group_id'=>$id,
				'status'=>$servObj::STATUS_PASS,
				'type'=>$servObj::TYPE_MATCH
			);
		$items = $servObj->where($map)->select();
		if(count($items)==0)
			$this->error('无有效的比赛列表，暂不能发布');

		$detail = $this->model->find($id);
		if(!($detail['competitor'] && $detail['score']) ){
			$this->error('发布前请先设置战队和比分');
		}

		$this->model->where(array('id'=>$id))->setField('state', intval($state));
		// 上报比赛状态
		event('ResourceGroup')->updateRace($id);
		$this->success('修改成功');
	}

	/**
	*仅用于后台编辑人员将之前设置的比赛转到新的比赛下
	*迁移完成后需要屏蔽该功能
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function migrate($id, $matchId){
		if(IS_POST){
			$raceIds = I('ids');
			$map = array('id'=>array('in', array_map('intval', $raceIds)));
			$res = D('Common/Video', 'Service')->where($map)->setField(array('group_id'=>intval($id)));
			if($res)
			 	$this->success('迁移成功');
			else
				$this->error('迁移失败');
		}else{
			$map = array(
					'match_id'=>intval($matchId),
				);
			$raceItems = D('Common/Video', 'Service')->where($map)
						->field('id,title,match_time,competitor,group_id')->select();
			foreach ($raceItems as $key => $value) {
				if(isset($value['group_id']) && $value['group_id'])
					unset($raceItems[$key]);
			}
			$this->races = $raceItems;

			$this->display();
		}
	}

	/**
	 * 推送比赛
	 * @author liubo <liubo@ilongyuan.com.cn>
	 */
	public function push($id)
	{
		$id = intval($id);
		if(IS_POST){
			$content = I('content');
			$data = A('Api/RaceGroup', 'Event')->info($id);

			$pEvent = event('Push');
			$pEvent->match($id, $content, $data['game_id']);

			$this->success('操作成功');
		}else{
			$data = A('Api/RaceGroup', 'Event')->info($id);
			empty($data) && $this->error('非法操作项');
			$this->assign($data);

			$this->display('push');
		}
	}

	/**
	*推荐的比赛视频列表
	*/
	public function recommend($id){
		$id = intval($id);
		$serVideo = D('Common/Video', 'Service');
		if(IS_POST){
			$data = I('videos');
			$raceIds = array();
			$videoIds = array();
			foreach ($data as $key => $value) {
				list($vid, $rid) = explode('&', $value);
				array_push($raceIds, intval($rid));
				array_push($videoIds, intval($vid));
			}
			$update = array('race_ids'=>$raceIds, 'video_ids'=>$videoIds);
			$flg = $this->model->where(array('id'=>$id))->save($update);
			if($flg===false)
				$this->error('操作失败');
			else
				$this->success('操作成功');

		}else{

			$grpInfo = $this->model->find($id);
			if($grpInfo['video_ids']){
				$vmap = array(
					'id'=>array('in', $grpInfo['video_ids']),
					'type'=>$serVideo::TYPE_NORMAL,
					'status'=>$serVideo::STATUS_PASS
				);
				$videos = $serVideo->where($vmap)->field('id,title')->select();
				$temp = array();
				foreach ($videos as $key => $value) {
					unset($value['_id']);
					$temp[$value['id']] = $value;
				}
				$videos = $temp;

				$rmap = array(
						'id'=>array('in', $grpInfo['race_ids']),
						'type'=>$serVideo::TYPE_MATCH,
						'status'=>$serVideo::STATUS_PASS
						);
				$races = $serVideo->where($rmap)->field('id,title,round')->select();
				$temp = array();
				foreach ($races as $key => $value) {
					unset($value['_id']);
					$temp[$value['id']] = $value;
				}
				$races = $temp;

				$temp=array();
				foreach ($grpInfo['video_ids'] as $key => $value) {
					$raceId = $grpInfo['race_ids'][$key];
					$temp[$key] = array(
									'video'=>$videos[$value],
									'race'=>$races[$raceId]
								);
				}

				$this->data = $temp;
			}
			
			$this->title = $grpInfo['title'];
			$this->display();

		}
	}

	public function _after_editRow($id, $data)
	{
		event('ResourceGroup')->updateRace($id);
	}
}